﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using compshop.web.CompShopDataService;
using System.Drawing;


namespace compshop.web
{
    public partial class EditOrderForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Application["DepartmentList"] = ObjectDataSource.csEntities.Departments.ToList<Department>();
            }

            List<Department> depList = Application["DepartmentList"] as List<Department>;
            ddlDepartment.DataSource = depList;
            ddlDepartment.DataTextField = "Name";
            ddlDepartment.DataBind();

            ProductList products = Session["Basket"] as ProductList;
            if (products != null)
            {
                int ind = 0;
                foreach (SimpleProduct sp in products)
                {
                    plholderOrder.Controls.Add(GetItem(sp, ind));
                    ind++;
                }
            }

            if (!Page.IsPostBack && products != null)
                lblSumma.Text = string.Format("{0:F2} грн.", products.GetSum());
        }

        private Control GetItem(SimpleProduct sp, int index)
        {
            Panel panel = new Panel();
            panel.BackColor = index % 2 == 0 ? Color.FromArgb(241, 250, 247) : Color.FromArgb(236, 247, 249);

            GeneralProduct genPrd = ObjectDataSource.csEntities.GeneralProducts.Expand("Producer").
                Where(x => x.GeneralProductID == sp.ProductID).First();

            Label lblName = new Label();
            lblName.Text = string.Format("{0}. {1} {2}", index + 1, genPrd.Producer.Name, genPrd.Name);
            lblName.Width = 250;
            panel.Controls.Add(lblName);

            Label lblPrice = new Label();
            lblPrice.Text = string.Format("  Цена: {0:F2} грн.", sp.Price);
            lblPrice.Width = 200;
            panel.Controls.Add(lblPrice);

            Label lblCount = new Label();
            lblCount.Text = "Кол-во: ";
            panel.Controls.Add(lblCount);

            DropDownList ddlCount = new DropDownList();
            ddlCount.ID = index.ToString();
            ddlCount.SelectedIndexChanged += new EventHandler(ddlCount_SelectedIndexChanged);
            ddlCount.AutoPostBack = true;

            int[] arr = new int[] { 1, 2, 3, 4, 5 };
            ddlCount.DataSource = arr;
            ddlCount.DataBind();
            panel.Controls.Add(ddlCount);

            if (sp.Count >= 5)
                ddlCount.SelectedIndex = 4;
            else
                if (sp.Count > 0)
                    ddlCount.SelectedIndex = sp.Count - 1;

            return panel;
        }

        protected void ddlCount_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            if (ddl != null)
            {
                ProductList products = Session["Basket"] as ProductList;
                int index;
                int.TryParse(ddl.ID, out index);

                int count;
                int.TryParse(ddl.SelectedValue, out count);
                products[index].Count = count;
                lblSumma.Text = string.Format("{0:F2} грн.", products.GetSum());
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Session["Basket"] = new ProductList();
            Response.Redirect("Default.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                Response.Write("<script>function window.onload() {  alert( 'Не все поля корректно заполнены!');}</script>");
                return;
            }

            ProductList products = Session["Basket"] as ProductList;
            if (products != null)
            {
                foreach (SimpleProduct sp in products)
                {
                    ObjectDataSource.AddOrder(0, sp.ProductID, sp.Count);
                }
            }

            //Здесь должна быть проверка ответа сервера базы данных
            //Если заказ занесен в базу
            Session["Basket"] = new ProductList();
            plholderOrder.Controls.Clear();
            tboxFname.Text = string.Empty;
            tboxLname.Text = string.Empty;
            tboxPhone.Text = string.Empty;
            lblSumma.Text = string.Format("{0:F2} грн.", 0);
            //Response.Write("<script>function window.onload() {  alert( 'Заказ оформлен.'); document.location.href =\"Default.aspx\"}</script>");
            Response.Redirect("ConfirmOrderForm.aspx");
        }

    }
}